package com.template.utils;

import org.springframework.lang.Nullable;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

public class CollectionUtils {

    public static boolean isEmpty(@Nullable Collection<?> collection) {
        return (collection == null || collection.isEmpty());
    }

    public static <K, V> Map<K, V> toMap(Collection<V> collection, Function<V, K> key) {
        HashMap<K, V> map = new HashMap<>();
        collection.forEach(coll -> {
            K apply = key.apply(coll);
            map.put(apply, coll);
        });
        return map;
    }

    public static <K, V, O> Map<K, V> toMap(Collection<O> collection, Function<O, K> getKey, Function<O, V> getValue) {
        HashMap<K, V> map = new HashMap<>();
        collection.forEach(coll -> {
            K key = getKey.apply(coll);
            V value = getValue.apply(coll);
            map.put(key, value);
        });
        return map;
    }

}
